package com.zdkj.subway.st.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwStAuditDTO;
import com.zdkj.subway.st.dto.in.SwTkPlanTempDecomposeDTO;
import com.zdkj.subway.st.entity.*;
import com.zdkj.subway.st.mapper.SwParamLineMapper;
import com.zdkj.subway.st.mapper.SwParamStationMapper;
import com.zdkj.subway.st.mapper.SwStTicketHandMapper;
import com.zdkj.subway.st.mapper.SwTkTicketDeliveryMapper;
import com.zdkj.subway.st.service.*;
import com.zdkj.subway.st.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/swStPlanTemp")
@Api(value = "swStPlanTemp", tags = "车票临时计划管理")
public class SwStPlanTempController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwStPlanTemp.class);
    private final SwStPlanTempService swStPlanTempService;
    private final SwTkTicketDeliveryDetailService swTkTicketDeliveryDetailService;
    private final SwTkTicketDeliveryMapper swTkTicketDeliveryMapper;
    private final SwStTicketHandMapper swStTicketHandMapper;
    private final SwStTicketHandDetailService swStTicketHandDetailService;
    private final SwStPlanDayService swStPlanDayService;
    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    @Resource
    private final SwPmTicketCardTypeService swPmTicketCardTypeService;
    @Resource
    private final SwPmTicketCardTypeParamService swPmTicketCardTypeParamService;
    @Autowired
    private GenSerialNo genSerialNo;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStPlanTempService.getById(id));
    }

    /**
     *
     * @param page 车票编码清洗计划调整菜单
     * @param swStPlanTemp
     * @param type 用于区分临时计划和临时计划分解与变更页面查询显示
     * @return
     */
    @GetMapping("/page")
    public R<IPage> getDictPage(Page page, SwStPlanTemp swStPlanTemp, String type) {
        String numbers = swStPlanTemp.getNumbers();
        swStPlanTemp.setNumbers(null);
        if(
                swStPlanTemp.getPlanStartTime()!=null&&!"".equals(swStPlanTemp.getPlanStartTime())&&
                swStPlanTemp.getPlanEndTime()!=null&&!"".equals(swStPlanTemp.getPlanEndTime())
        ){
            String planStartTime = swStPlanTemp.getPlanStartTime();
            String planEndTime = swStPlanTemp.getPlanEndTime();
            swStPlanTemp.setPlanStartTime(null);
            swStPlanTemp.setPlanEndTime(null);
            LambdaQueryWrapper<SwStPlanTemp> lambdaQueryWrapper = Wrappers.query(swStPlanTemp).lambda();
            lambdaQueryWrapper.and(wq -> wq
                            .eq(SwStPlanTemp::getPlanType,"1")
                            .or()
                            .eq(SwStPlanTemp::getPlanType,"2")
                    )
                    .ge(SwStPlanTemp::getPlanStartTime,planStartTime)
                    .le(SwStPlanTemp::getPlanEndTime,planEndTime)
                    .eq(StringUtils.isEmpty(type),SwStPlanTemp::getIsDecompose,"0").like(StringUtils.isNotEmpty(numbers),SwStPlanTemp::getNumbers,numbers);
            return R.ok(swStPlanTempService.page(page, lambdaQueryWrapper.orderByDesc(SwStPlanTemp::getPlanStartTime)));
        }else{
            LambdaQueryWrapper<SwStPlanTemp> lambdaQueryWrapper = Wrappers.query(swStPlanTemp).lambda();
            lambdaQueryWrapper.and(wq -> wq
                    .eq(SwStPlanTemp::getPlanType,"1")
                    .or()
                    .eq(SwStPlanTemp::getPlanType,"2")
            ).eq(StringUtils.isEmpty(type),SwStPlanTemp::getIsDecompose,"0").like(StringUtils.isNotEmpty(numbers),SwStPlanTemp::getNumbers,numbers);
            return R.ok(swStPlanTempService.page(page, lambdaQueryWrapper.orderByDesc(SwStPlanTemp::getPlanStartTime)));
        }
    }

    /**
     * 车票配收计划调整页面
     * @param page
     * @param swStPlanTemp
     * @return
     */
    @GetMapping("/page/delivery")
    public R<IPage> getDeliveryPage(Page page, SwStPlanTemp swStPlanTemp) {
        if(
                swStPlanTemp.getPlanStartTime()!=null&&!"".equals(swStPlanTemp.getPlanStartTime())&&
                        swStPlanTemp.getPlanEndTime()!=null&&!"".equals(swStPlanTemp.getPlanEndTime())
        ){
            String planStartTime = swStPlanTemp.getPlanStartTime();
            String planEndTime = swStPlanTemp.getPlanEndTime();
            swStPlanTemp.setPlanStartTime(null);
            swStPlanTemp.setPlanEndTime(null);
            LambdaQueryWrapper<SwStPlanTemp> lambdaQueryWrapper = Wrappers.query(swStPlanTemp).lambda();
            lambdaQueryWrapper.and(wq -> wq
                            .eq(SwStPlanTemp::getPlanType,"3")
                            .or()
                            .eq(SwStPlanTemp::getPlanType,"4")
                    )
                    .ge(SwStPlanTemp::getPlanStartTime,planStartTime)
                    .le(SwStPlanTemp::getPlanEndTime,planEndTime);
            return R.ok(swStPlanTempService.page(page, lambdaQueryWrapper.orderByDesc(SwStPlanTemp::getPlanStartTime)));
        }else{
            LambdaQueryWrapper<SwStPlanTemp> lambdaQueryWrapper = Wrappers.query(swStPlanTemp).lambda();
            lambdaQueryWrapper.and(wq -> wq
                    .eq(SwStPlanTemp::getPlanType,"3")
                    .or()
                    .eq(SwStPlanTemp::getPlanType,"4")
            );
            return R.ok(swStPlanTempService.page(page, lambdaQueryWrapper.orderByDesc(SwStPlanTemp::getPlanStartTime)));
        }
    }


    @GetMapping("/page/update")
    @SysLog("清洗生产临时计划修改记录查询")
    public R<IPage> getDictPageByUpdate(Page page, SwStPlanTemp swStPlanTemp) {
        SwStPlanTemp init = new SwStPlanTemp();
        return R.ok(swStPlanTempService.page(page, Wrappers.query(init).lambda()
                .and(wq -> wq
                    .eq(SwStPlanTemp::getPlanType,"1")
                    .or()
                    .eq(SwStPlanTemp::getPlanType,"2")
                )
                .ge(swStPlanTemp.getPlanStartTime() == null ? false : true, SwStPlanTemp::getPlanStartTime, swStPlanTemp.getPlanStartTime())
                .le(swStPlanTemp.getPlanEndTime() == null ? false : true, SwStPlanTemp::getPlanEndTime, swStPlanTemp.getPlanEndTime())
                .eq(swStPlanTemp.getTicketType() == null ? false : true, SwStPlanTemp::getTicketType, swStPlanTemp.getTicketType())
                .eq(swStPlanTemp.getTicketName() == null ? false : true, SwStPlanTemp::getTicketName, swStPlanTemp.getTicketName())
                //.eq(SwStPlanTemp::getIsDecompose, SubwayStConstants.COMPOSE_STATUS_COMFIRM)
                .isNotNull(SwStPlanTemp::getTicketNumberNow)));
    }

    @GetMapping("/page/deliveryUpdate")
    @SysLog("配送回收临时计划修改记录查询")
    public R<IPage> getDeliveryPageByUpdate(Page page, SwStPlanTemp swStPlanTemp) {
        SwStPlanTemp init = new SwStPlanTemp();
        return R.ok(swStPlanTempService.page(page, Wrappers.query(init).lambda()
                .and(wq -> wq
                        .eq(SwStPlanTemp::getPlanType,"3")
                        .or()
                        .eq(SwStPlanTemp::getPlanType,"4")
                )
                .ge(swStPlanTemp.getPlanStartTime() == null ? false : true, SwStPlanTemp::getPlanStartTime, swStPlanTemp.getPlanStartTime())
                .le(swStPlanTemp.getPlanEndTime() == null ? false : true, SwStPlanTemp::getPlanEndTime, swStPlanTemp.getPlanEndTime())
                .eq(swStPlanTemp.getTicketType() == null ? false : true, SwStPlanTemp::getTicketType, swStPlanTemp.getTicketType())
                .eq(swStPlanTemp.getTicketName() == null ? false : true, SwStPlanTemp::getTicketName, swStPlanTemp.getTicketName())
                .eq(SwStPlanTemp::getIsDecompose, SubwayStConstants.COMPOSE_STATUS_COMFIRM)
                .isNotNull(SwStPlanTemp::getTicketNumberNow)));
    }

    @SysLog("新增车票临时计划")
    @PostMapping
    public R save(@Valid @RequestBody SwStPlanTemp swStPlanTemp) {
        String L= "L";//临时计划标识
        PigxUser user = SecurityUtils.getUser();
        swStPlanTemp.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
        swStPlanTemp.setIsSend(SubwayStConstants.SEND_STATUS_NO);
        swStPlanTemp.setCreatorId((long) user.getId());
        swStPlanTemp.setCreatorName(user.getUsername());
        if("1".equals(swStPlanTemp.getPlanType())){
            //清洗计划类型
            //生成单号
            //--临时计划
            String generateNum = genSerialNo.generateNum(L + swStPlanTemp.getPlanType());
            swStPlanTemp.setNumbers(generateNum);
        }else if("2".equals(swStPlanTemp.getPlanType())){
            //生产计划类型
            //生成单号
            //--临时计划
            String generateNum = genSerialNo.generateNum(L + swStPlanTemp.getPlanType());
            swStPlanTemp.setNumbers(generateNum);
        }
        return R.ok(swStPlanTempService.save(swStPlanTemp));
    }

    @SysLog("批量新增车票临时计划")
    @PostMapping("/saveAll")
    public R saveAll(@Valid @RequestBody List<SwStPlanTemp> swStPlanTempList) {
        PigxUser user = SecurityUtils.getUser();
        for (SwStPlanTemp swStPlanTemp : swStPlanTempList) {
            swStPlanTemp.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
            swStPlanTemp.setCreatorId((long) user.getId());
            swStPlanTemp.setCreatorName(user.getUsername());
            swStPlanTempService.save(swStPlanTemp);
        }
        return R.ok(swStPlanTempList.size());
    }

    @SysLog("删除车票临时计划")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable String id) {
        return R.ok(swStPlanTempService.removeById(id));
    }

    @PutMapping
    @SysLog("修改车票临时计划")
    public R updateById(@Valid @RequestBody SwStPlanTemp swStPlanTemp) {
        return R.ok(swStPlanTempService.updateById(swStPlanTemp));
    }

    @PutMapping("/sendBatch")
    @SysLog("批量下发车票临时计划")
    public R sendBatch(@Valid @RequestBody List<Integer> ids) {
        return R.ok(swStPlanTempService.update(Wrappers.<SwStPlanTemp>lambdaUpdate()
                .in(SwStPlanTemp::getId, ids)
                .set(SwStPlanTemp::getIsSend, SubwayStConstants.SEND_STATUS_YES)));
    }

    @PutMapping("/submit")
    @SysLog("批量提交车票临时计划")
    public R submitBatch(@RequestBody List<Integer> ids) {
        return R.ok(swStPlanTempService.update(Wrappers.<SwStPlanTemp>lambdaUpdate()
                .in(SwStPlanTemp::getId, ids)
                .in(SwStPlanTemp::getCheckStatus, SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT, SubwayStConstants.AUDIT_STATUS_FAIL)
                .set(SwStPlanTemp::getCheckStatus, SubwayStConstants.AUDIT_STATUS_WAIT)));
    }

    @PutMapping("/audit")
    @SysLog("批量审核车票临时计划")
    public R auditBatch(@RequestBody SwStAuditDTO swStAuditDTO) {
        String checkStatus = swStAuditDTO.getResult() ? SubwayStConstants.AUDIT_STATUS_PASS :
                SubwayStConstants.AUDIT_STATUS_FAIL;
        swStPlanTempService.update(Wrappers.<SwStPlanTemp>lambdaUpdate()
                .in(SwStPlanTemp::getId, swStAuditDTO.getIds())
                .eq(SwStPlanTemp::getCheckStatus, SubwayStConstants.AUDIT_STATUS_WAIT)
                .set(SwStPlanTemp::getCheckStatus, checkStatus)
                .set(SwStPlanTemp::getCheckReason, swStAuditDTO.getSuggestions()));

        swStAuditDTO.getIds().forEach(item -> {
            SwStPlanTemp SwStPlanTemp = swStPlanTempService.getById(item);
            if(SwStPlanTemp != null && SwStPlanTemp.getCheckStatus().equals(SubwayStConstants.AUDIT_STATUS_PASS)){
                //临时配送计划
                if("3".equals(SwStPlanTemp.getPlanType())){
                    SwTkTicketDelivery swTkTicketDelivery = new SwTkTicketDelivery();
                    SwTkTicketDeliveryDetail swTkTicketDeliveryDetail = new SwTkTicketDeliveryDetail();
                    PigxUser user = SecurityUtils.getUser();
                    swTkTicketDelivery.setLineCode(SwStPlanTemp.getLineCode());
                    swTkTicketDelivery.setStationCode(SwStPlanTemp.getStationCode());
                    swTkTicketDelivery.setDeliveryPersonName(SwStPlanTemp.getDistributor());
                    swTkTicketDelivery.setDeliveryPersonCode(SwStPlanTemp.getDistributorCode());
                    swTkTicketDelivery.setDeliveryPersonTwoName(SwStPlanTemp.getDistributorTwo());
                    swTkTicketDelivery.setDeliveryPersonTwoCode(SwStPlanTemp.getDistributorCodeTwo());
                    //swTkTicketDelivery.setDeliveryPersonName(user.getNikeName());
                    //swTkTicketDelivery.setDeliveryPersonCode(user.getUserCode());
                    swTkTicketDelivery.setDataSource("2");//临时配送计划
                    if(SwStPlanTemp.getTicketNumberNow()!=null){//如果计划张数为null，取TicketNumber
                        swTkTicketDelivery.setDeliveryCount(SwStPlanTemp.getTicketNumberNow());
                    }else {
                        swTkTicketDelivery.setDeliveryCount(SwStPlanTemp.getTicketNumber());
                    }
                    swTkTicketDelivery.setDeliveryTime(DateUtilsSt.LocalDateTimeToString(SwStPlanTemp.getPlanStartTime()));
                    swTkTicketDelivery.setCreatorName(user.getNikeName());
                    swTkTicketDelivery.setCreatorId(user.getId());
                    swTkTicketDelivery.setDelFlag("0");
                    int insert = swTkTicketDeliveryMapper.insert(swTkTicketDelivery);
                    String delFlag = swTkTicketDelivery.getDelFlag();
                    if(insert == 1 && "0".equals(delFlag)){
                        swTkTicketDeliveryDetail.setRefId(swTkTicketDelivery.getId());//关联配送子表
                        swTkTicketDeliveryDetail.setTicketType(SwStPlanTemp.getTicketType());
                        swTkTicketDeliveryDetail.setTicketTypeParam(SwStPlanTemp.getTicketName());
                        swTkTicketDeliveryDetail.setTicketAmount(SwStPlanTemp.getTicketPrice());
                        swTkTicketDeliveryDetail.setTicketCount(String.valueOf(SwStPlanTemp.getTicketTimes()));
                        if(SwStPlanTemp.getTicketNumberNow()!=null){//如果计划张数为null，取TicketNumber
                            swTkTicketDeliveryDetail.setDeliveryCount(SwStPlanTemp.getTicketNumberNow());
                        }else {
                            swTkTicketDeliveryDetail.setDeliveryCount(SwStPlanTemp.getTicketNumber());
                        }
                        swTkTicketDeliveryDetail.setRemark(SwStPlanTemp.getRemark());
                        swTkTicketDeliveryDetail.setCardNumber(SwStPlanTemp.getActiveTime());
                        swTkTicketDeliveryDetailService.save(swTkTicketDeliveryDetail);
                    }
                }
                //临时回收计划
                if("4".equals(SwStPlanTemp.getPlanType())){
                    SwStTicketHand swStTicketHand = new SwStTicketHand();
                    SwStTicketHandDetail swStTicketHandDetail = new SwStTicketHandDetail();
                    PigxUser user = SecurityUtils.getUser();
                    swStTicketHand.setLineCode(SwStPlanTemp.getLineCode());
                    swStTicketHand.setStationCode(SwStPlanTemp.getStationCode());
                    swStTicketHand.setReceivePersonName(SwStPlanTemp.getDistributor());
                    swStTicketHand.setReceivePersonCode(SwStPlanTemp.getDistributorCode());
                    swStTicketHand.setReceivePersonTwoName(SwStPlanTemp.getDistributorTwo());
                    swStTicketHand.setReceivePersonTwoCode(SwStPlanTemp.getDistributorCodeTwo());
                    //swStTicketHand.setReceivePersonName(user.getNikeName());
                    //swStTicketHand.setReceivePersonCode(user.getUserCode());
                    swStTicketHand.setDataSource("2");//临时配送计划
                    swStTicketHand.setSubmitStatus("1");
                    swStTicketHand.setNoticeStatus("0");
                    swStTicketHand.setNoticeConfirm("0");
                    swStTicketHand.setHandStatus("0");
                    if(SwStPlanTemp.getTicketNumberNow()!=null){//如果计划张数为null，取TicketNumber
                        swStTicketHand.setReceiveCount(SwStPlanTemp.getTicketNumberNow());
                    }else {
                        swStTicketHand.setReceiveCount(SwStPlanTemp.getTicketNumber());
                    }
                    swStTicketHand.setReceiveTime(DateUtilsSt.LocalDateTimeToString(SwStPlanTemp.getPlanStartTime()));//回收时间
                    swStTicketHand.setHandTime(DateUtilsSt.LocalDateTimeToString(SwStPlanTemp.getPlanStartTime()));//上交时间
                    swStTicketHand.setCreatorName(user.getNikeName());
                    swStTicketHand.setCreatorId(user.getId());
                    swStTicketHand.setDeptId(user.getDeptId());
                    swStTicketHand.setDelFlag("0");
                    int insert = swStTicketHandMapper.insert(swStTicketHand);
                    String delFlag = swStTicketHand.getDelFlag();
                    if(insert == 1 && "0".equals(delFlag)){
                        swStTicketHandDetail.setRefId(swStTicketHand.getId());//关联配送子表
                        swStTicketHandDetail.setTicketType(SwStPlanTemp.getTicketType());
                        swStTicketHandDetail.setTicketName(SwStPlanTemp.getTicketName());
                        swStTicketHandDetail.setTicketAmount(SwStPlanTemp.getTicketPrice());
                        swStTicketHandDetail.setTicketCount(String.valueOf(SwStPlanTemp.getTicketTimes()));
                        if(SwStPlanTemp.getTicketNumberNow()!=null){//如果计划张数为null，取TicketNumber
                            swStTicketHandDetail.setReceiveCount(SwStPlanTemp.getTicketNumberNow());
                        }else {
                            swStTicketHandDetail.setReceiveCount(SwStPlanTemp.getTicketNumber());
                        }
                        swStTicketHandDetail.setRemark(SwStPlanTemp.getRemark());
                        swStTicketHandDetail.setCardNumber(SwStPlanTemp.getActiveTime());//有效期
                        swStTicketHandDetailService.save(swStTicketHandDetail);
                    }
                }
                //临时清洗生产计划
                if("1".equals(SwStPlanTemp.getPlanType())||"2".equals(SwStPlanTemp.getPlanType())){
                    SwStPlanDay swStPlanDay = new SwStPlanDay();
                    PigxUser user = SecurityUtils.getUser();
                    swStPlanDay.setWorkTime(SwStPlanTemp.getPlanEndTime().substring(0,4));//年
                    if(Integer.parseInt(SwStPlanTemp.getPlanEndTime().substring(5,7))<10){
                        swStPlanDay.setPlanMonth(SwStPlanTemp.getPlanEndTime().substring(6,7));//月
                    }else{
                        swStPlanDay.setPlanMonth(SwStPlanTemp.getPlanEndTime().substring(5,7));//月
                    }
                    swStPlanDay.setPlanWeek(DateUtilsSt.whatWeek(SwStPlanTemp.getPlanEndTime()));//周
                    swStPlanDay.setTicketType(SwStPlanTemp.getTicketType());
                    swStPlanDay.setTicketName(SwStPlanTemp.getTicketName());
                    swStPlanDay.setLineCode(SwStPlanTemp.getLineCode());
                    swStPlanDay.setStationCode(SwStPlanTemp.getStationCode());
                    swStPlanDay.setTicketPrice(SwStPlanTemp.getTicketPrice());
                    swStPlanDay.setTicketTimes(SwStPlanTemp.getTicketTimes());
                    if("1".equals(SwStPlanTemp.getPlanType())){
                        swStPlanDay.setPlanType("1");//清洗计划类型
                    }else if("2".equals(SwStPlanTemp.getPlanType())){
                        swStPlanDay.setPlanType("2");//生产计划类型
                    }
                    //单号
                    swStPlanDay.setNumbers(SwStPlanTemp.getNumbers());
                    swStPlanDay.setDisplay(true);
                    swStPlanDay.setDataSource("3");//数据来源:0:周计划分解;1:无效票;2:公务票;3:临时计划
                    swStPlanDay.setLatestStartTime(SwStPlanTemp.getLatestStartTime());
                    if(SwStPlanTemp.getTicketNumberNow()!=null){//如果计划张数为null，取TicketNumber
                        swStPlanDay.setTicketNumber(SwStPlanTemp.getTicketNumberNow());
                    }else {
                        swStPlanDay.setTicketNumber(SwStPlanTemp.getTicketNumber());
                    }
                    swStPlanDay.setStartEndNo(SwStPlanTemp.getStartEndNo());
                    swStPlanDay.setPlanFinishTime(DateUtilsSt.LocalDateTimeToString(SwStPlanTemp.getPlanEndTime()));
                    swStPlanDay.setCheckStatus("0");
                    swStPlanDay.setCreatorName(user.getUsername());
                    swStPlanDay.setCreatorId(user.getId().longValue());
                    swStPlanDay.setPersonName(SwStPlanTemp.getTicketCoder());//车票编码员
                    swStPlanDay.setPersonId(SwStPlanTemp.getTicketCoderCode());
                    swStPlanDay.setActiveTime(SwStPlanTemp.getActiveTime());//车票有效期
                    swStPlanDayService.save(swStPlanDay);
                }
            }
        });
        return R.ok();
    }

    @PostMapping("/compose")
    @SysLog("确认车票临时计划分解")
    public R confirmCompose(@Valid @RequestBody SwStPlanTemp swStPlanTemp) {
        swStPlanTemp.setIsDecompose(SubwayStConstants.COMPOSE_STATUS_COMFIRM);
        return R.ok(swStPlanTempService.updateById(swStPlanTemp));
    }

    @PostMapping("/decompose")
    @SysLog("临时计划分解")
    public R decompose(@RequestBody SwTkPlanTempDecomposeDTO planTempDecomposeDTO){
        return R.ok(swStPlanTempService.decompose(planTempDecomposeDTO));
    }

    @ApiOperation(value = "导出临时计划", notes = "导出临时计划")
    @GetMapping("/export")
    @SysLog("导出临时计划")
    public void exportExcel(SwStPlanTemp swStPlanTemp, HttpServletResponse response) throws IOException {
        List<SwStPlanTemp> swTkStockFlowList = swStPlanTempService.list(Wrappers.query(swStPlanTemp));
        String fileName = URLEncoder.encode("临时计划", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStPlanTemp.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("临时计划").doWrite(swTkStockFlowList);
    }


    /**
     * 车票临时计划配送信息模板下载
     * @param
     * @return
     * @throws
     */
    @ApiOperation(value = "车票临时计划配送信息模板下载", notes = "车票临时计划配送信息模板下载")
    @GetMapping("/exportTamplateDeliveryTemp")
    public void exportTamplateDeliveryTemp(HttpServletResponse response) {
        swStPlanTempService.exportTamplateDeliveryTemp(response);
    }

    /**
     * 车票临时计划配送信息导入
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "车票临时计划配送信息导入", notes = "车票临时计划配送信息导入")
    @SysLog("车票临时计划配送信息导入")
    @PostMapping({ "/ImportDeliveryTemp" })
    @Transactional(rollbackFor = Exception.class)
    public R ImportDeliveryTemp(@RequestParam("file") final MultipartFile file) throws Exception {

        final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            MultipartFileToFile.delteTempFile(excelFile);
            List<SwStPlanTemp> excelDvoList = new ArrayList<>();//处理数据表

            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                SwStPlanTemp excelDvo = new SwStPlanTemp();
                //计划类型
                if(ObjectUtil.isEmpty(data.get(0))){
                    return R.failed("导入失败，请检查【计划类型】后重新导入！");
                }
                if("配送计划".equals(String.valueOf(data.get(0)))){
                    excelDvo.setPlanType("3");
                }
                if("回收计划".equals(String.valueOf(data.get(0)))){
                    excelDvo.setPlanType("4");
                }
                if(ObjectUtil.isEmpty(data.get(1))){
                    return R.failed("导入失败，请检查【线路】后重新导入！");
                }else {
                    SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getName, data.get(1)));
                    if(ObjectUtil.isEmpty(swParamLine)){
                        return R.failed("导入失败，请检查【线路】后重新导入！");
                    }
                    excelDvo.setLineCode(swParamLine.getCode());//线路
                }

                if(ObjectUtil.isEmpty(data.get(2))){
                    return R.failed("导入失败，请检查【站点】后重新导入！");
                }else {
                    SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                            .eq(SwParamStation::getLineCode, excelDvo.getLineCode()).eq(SwParamStation::getName, data.get(2)));
                    if(ObjectUtil.isEmpty(swParamStation)){
                        return R.failed("导入失败，请检查【站点】后重新导入！");
                    }
                    excelDvo.setStationCode(swParamStation.getCode());//站点
                }


                if(ObjectUtil.isNotEmpty(data.get(7))){
                    SwPmTicketCardType swPmTicketCardType = swPmTicketCardTypeService.getOne(Wrappers.<SwPmTicketCardType>lambdaQuery().eq(SwPmTicketCardType::getMainName, data.get(7)));
                    excelDvo.setTicketType(getStringData(swPmTicketCardType.getMainEnName()));//票种
                }

                if(ObjectUtil.isNotEmpty(data.get(8))){
                    SwPmTicketCardTypeParam swPmTicketCardTypeParam = swPmTicketCardTypeParamService.getOne(Wrappers.<SwPmTicketCardTypeParam>lambdaQuery()
                            .eq(SwPmTicketCardTypeParam::getSubName,data.get(8)));
                    excelDvo.setTicketName(getStringData(swPmTicketCardTypeParam.getSubEnName()));//车票名称
                }

                excelDvo.setDistributor(getStringData(data.get(3)));//配送人1
                excelDvo.setDistributorCode(getStringData(data.get(4)));//配送人工号1
                excelDvo.setDistributorTwo(getStringData(data.get(5)));//配送人2
                excelDvo.setDistributorCodeTwo(getStringData(data.get(6)));//配送人工号2

                excelDvo.setTicketPrice(getData(data.get(9)));//票价
                excelDvo.setTicketTimes(data.get(10) == null ? 0 : Integer.parseInt(data.get(10)));//次数
                excelDvo.setTicketNumber(data.get(11) == null ? 0 : Integer.parseInt(data.get(11)));//张数

                if(ObjectUtil.isEmpty(data.get(12))){
                    return R.failed("导入失败，请检查【时间格式】后重新导入！");
                }
                excelDvo.setPlanStartTime(String.valueOf(data.get(12)));//计划开始时间

                if(ObjectUtil.isEmpty(data.get(13))){
                    return R.failed("导入失败，请检查【时间格式】后重新导入！");
                }
                excelDvo.setPlanEndTime(String.valueOf(data.get(13)));//计划结束时间

                excelDvo.setRemark(getStringData(data.get(14)));//备注
                PigxUser user = SecurityUtils.getUser();
                excelDvo.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
                excelDvo.setIsSend(SubwayStConstants.SEND_STATUS_NO);
                excelDvo.setCreatorId((long) user.getId());
                excelDvo.setCreatorName(user.getUsername());
                excelDvoList.add(excelDvo);

            }
            if(CollectionUtil.isNotEmpty(excelDvoList)){
                swStPlanTempService.saveBatch(excelDvoList);
            }
        }
        return R.ok();
    }

    /**
     * 通过id批量删除
     * @param idList id
     * @return R
     */
    @ApiOperation(value = "批量删除未下发的数据", notes = "批量删除未下发的数据")
    @SysLog("批量删除未下发的数据")
    @DeleteMapping("/delBatch")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        return R.ok(swStPlanTempService.removeByIds(idList));
    }

    private String getStringData(String param){
        if(ObjectUtil.isEmpty(param)){
            return "";
        }
        return param;
    }
    private BigDecimal getData(String money){
        try {
            BigDecimal itemMoney = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
            return itemMoney;
        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
	 /**
     * 临时日计划模板下载
     * @param
     * @return
     * @throws
     */
    @ApiOperation(value = "临时日计划模板下载", notes = "临时日计划模板下载")
    @GetMapping("/exportTamplatePlan")
    public void exportTamplatePlan(HttpServletResponse response) {
        swStPlanTempService.exportTamplatePlan(response);
    }
    /**
     * 临时日计划导入
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "临时日计划导入", notes = "临时日计划导入")
    @SysLog("临时日计划导入")
    @PostMapping({ "/ImportTempPlan" })
    @Transactional(rollbackFor = Exception.class)
    public R ImportTempPlan(@RequestParam("file") final MultipartFile file) throws Exception {
        String L= "L";//临时计划标识
        final File excelFile = MultipartFileToFile.multipartFileToFile(file);
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            MultipartFileToFile.delteTempFile(excelFile);
            List<SwStPlanTemp> excelDvoList = new ArrayList<>();//处理数据表

            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                SwStPlanTemp excelDvo = new SwStPlanTemp();
                //计划类型
                if(ObjectUtil.isEmpty(data.get(0))){
                    return R.failed("导入失败，请检查【计划类型】后重新导入！");
                }
                if("清洗计划".equals(String.valueOf(data.get(0)))){
                    excelDvo.setPlanType("1");
                }
                if("生产计划".equals(String.valueOf(data.get(0)))){
                    excelDvo.setPlanType("2");
                }
				/*
                if(ObjectUtil.isEmpty(data.get(1))){
                    return R.failed("导入失败，请检查【线路】后重新导入！");
                }else {
                    SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getName, data.get(1)));
                    if(ObjectUtil.isEmpty(swParamLine)){
                        return R.failed("导入失败，请检查【线路】后重新导入！");
                    }
                    excelDvo.setLineCode(swParamLine.getCode());//线路
                }

                if(ObjectUtil.isEmpty(data.get(2))){
                    return R.failed("导入失败，请检查【站点】后重新导入！");
                }else {
                    SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                            .eq(SwParamStation::getLineCode, excelDvo.getLineCode()).eq(SwParamStation::getName, data.get(2)));
                    if(ObjectUtil.isEmpty(swParamStation)){
                        return R.failed("导入失败，请检查【站点】后重新导入！");
                    }
                    excelDvo.setStationCode(swParamStation.getCode());//站点
                }
                */

                if(ObjectUtil.isNotEmpty(data.get(1))){
                    SwPmTicketCardType swPmTicketCardType = swPmTicketCardTypeService.getOne(Wrappers.<SwPmTicketCardType>lambdaQuery().eq(SwPmTicketCardType::getMainName, data.get(1)));
                    excelDvo.setTicketType(getStringData(swPmTicketCardType.getMainEnName()));//票种
                }

                if(ObjectUtil.isNotEmpty(data.get(2))){
                    SwPmTicketCardTypeParam swPmTicketCardTypeParam = swPmTicketCardTypeParamService.getOne(Wrappers.<SwPmTicketCardTypeParam>lambdaQuery()
                            .eq(SwPmTicketCardTypeParam::getSubName,data.get(2)));
                    excelDvo.setTicketName(getStringData(swPmTicketCardTypeParam.getSubEnName()));//车票名称
                }
                /*
                excelDvo.setDistributor(getStringData(data.get(3)));//配送人1
                excelDvo.setDistributorCode(getStringData(data.get(4)));//配送人工号1
                excelDvo.setDistributorTwo(getStringData(data.get(5)));//配送人2
                excelDvo.setDistributorCodeTwo(getStringData(data.get(6)));//配送人工号2
				*/

                excelDvo.setTicketPrice(getData(data.get(3)));//票价
                excelDvo.setTicketTimes(data.get(4) == null ? 0 : Integer.parseInt(data.get(4)));//次数
                excelDvo.setTicketNumber(data.get(5) == null ? 0 : Integer.parseInt(data.get(5)));//张数
                
				if(ObjectUtil.isNotEmpty(data.get(6))){
				  excelDvo.setStartEndNo(data.get(6));
				}

                excelDvo.setActiveTime(data.get(7) == null ? "" : data.get(7));//车票有效期
              

				if(ObjectUtil.isEmpty(data.get(8))){
                    return R.failed("导入失败，请检查车票最晚使用时间【时间格式】后重新导入！");
                }
				
                excelDvo.setLatestStartTime(DateUtilsSt.stringTolocalDateTime(String.valueOf(data.get(8))));//车票最晚使用时间,-------需要转换为LocalDateTime


                if(ObjectUtil.isEmpty(data.get(9))){
                    return R.failed("导入失败，请检查计划开始时间【时间格式】后重新导入！");
                }
                excelDvo.setPlanStartTime(String.valueOf(data.get(9)));//计划开始时间


                if(ObjectUtil.isEmpty(data.get(10))){
                    return R.failed("导入失败，请检查计划结束时间【时间格式】后重新导入！");
                }
                excelDvo.setPlanEndTime(String.valueOf(data.get(10)));//计划结束时间

                excelDvo.setRemark(getStringData(data.get(11)));//备注
                //设置单号
				 if("1".equals(excelDvo.getPlanType())){
					//清洗计划类型
					//生成单号
					//--临时计划
					String generateNum = genSerialNo.generateNum(L + excelDvo.getPlanType());
					excelDvo.setNumbers(generateNum);
				}else if("2".equals(excelDvo.getPlanType())){
					//生产计划类型
					//生成单号
					//--临时计划
					String generateNum = genSerialNo.generateNum(L + excelDvo.getPlanType());
					excelDvo.setNumbers(generateNum);
				}

                PigxUser user = SecurityUtils.getUser();
                excelDvo.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
                excelDvo.setIsSend(SubwayStConstants.SEND_STATUS_YES);
                excelDvo.setCreatorId((long) user.getId());
                excelDvo.setCreatorName(user.getUsername());
                excelDvoList.add(excelDvo);

            }
            if(CollectionUtil.isNotEmpty(excelDvoList)){
                swStPlanTempService.saveBatch(excelDvoList);
            }
        }
        return R.ok();
    }

}
